package org.example.base.common.service.impl;

import com.alibaba.fastjson2.JSONObject;
import org.example.base.common.dao.TRoleDao;
import org.example.base.common.entity.TRoleEntity;
import org.example.base.common.model.TRoleMenuModel;
import org.example.base.common.model.TRoleModel;
import org.example.base.common.model.TUserRoleModel;
import org.example.base.common.service.TRoleMenuService;
import org.example.base.common.service.TRoleService;
import org.example.core.exception.ErrorException;
import org.example.core.mysql.Where;
import org.example.core.service.impl.SimpleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2024/1/12 23:53
 */
@Primary
@Service
public class TRoleServiceImpl extends SimpleServiceImpl<String, TRoleModel, TRoleEntity> implements TRoleService {

    @Autowired
    private TRoleMenuService tRoleMenuService;

    @Autowired
    private TRoleDao tRoleDao;

    @Override
    public void addMenus(Map<String, Object> params) {
        Object menuIds = params.get("menuIds");
        Object roleId = params.get("roleId");
        //删除之前该用户的
        List<TRoleMenuModel> tRoleMenuModelList = tRoleMenuService.search(Where.build().field("role_id").equal(roleId));
        tRoleMenuModelList.stream().map(TRoleMenuModel::getId).forEach(roleMenuId->{
            tRoleMenuService.delete(roleMenuId);
        });
        List<String> menuIdList = (List<String>) menuIds;
        tRoleDao.addMenus(menuIdList,roleId);
    }

    @Override
    public JSONObject getDetail(String id) {
        TRoleModel roleModel = getById(id);
        JSONObject roleModelJsonObject = JSONObject.parseObject(JSONObject.toJSONString(roleModel));
        roleModelJsonObject.put("menuIds",tRoleMenuService.search(Where.build().field("role_id").equal(id)).stream().map(TRoleMenuModel::getMenuId).collect(Collectors.toList()));
        return roleModelJsonObject;
    }
}
